package controller

import (
	"github.com/gin-gonic/gin"
	"go-demo/mvc/model"
	"go-demo/mvc/service"
	"go-demo/utils"
	"net/http"
)

type UserController struct {
	UserService *service.UserService
}

func NewUserController(userService *service.UserService) *UserController {
	return &UserController{UserService: userService}
}

func (uc UserController) Register(c *gin.Context) {
	var registerForm model.RegisterForm
	if err := utils.Jons2Type(c, &registerForm); err != nil {
		return // 参数绑定失败，响应已在 BindJSON 中处理
	}

	err := uc.UserService.Register(&registerForm)
	if err != nil {
		utils.Fail(c, http.StatusBadRequest, err.Error())
		return
	}
	utils.Success(c, "User registered successfully")
}

func (uc UserController) Login(c *gin.Context) {
	var loginForm model.LoginForm
	if err := utils.Jons2Type(c, &loginForm); err != nil {
		return
	}
	token, err := uc.UserService.Login(&loginForm)
	if err != nil {
		utils.Fail(c, http.StatusUnauthorized, err.Error())
		return
	}
	utils.Success(c, gin.H{"token": token})
}
